/* cel memory operation module implements functions source file.
 * @author chenxin <chenxin619315@gmail.com>
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include "stdiolib.h"

/* swap the content between a and b for specified bytes */
void cel_mem_swap(void *a, void *b, int size)
{
	unsigned char * __a = a;
	unsigned char * __b = b;
	unsigned char temp;

	while ( size-- > 0 ) 
	{
		temp = *__a;	
		*__a++ = *__b;
		*__b++ = temp;
	}
}

/* copy specified bytes from source to the destination */
void cel_mem_copy( void *_src, void *_dst, int size)
{
	unsigned char * __src = _src;
	unsigned char * __dst = _dst;

	while ( size-- > 0 )
	{
		*__dst++ = *__src++;
	}
}

/* print the content with forms of bits */
void cel_mem_bits(const char *name, const void *ptr, unsigned int __bytes)
{
	unsigned int i;
	unsigned char *str = (unsigned char  *)ptr;
	unsigned int length = __bytes * CHAR_BIT;

	if(name != NULL) 
		printf("%s ", name);

	for(i = 0; i < length;)
	{
		if(CEL_BIT_FETCH(str, i) != 0)
			printf("1");
		else
			printf("0");

		if((++i % 8) == 0) 
			printf(" ");
	}
	printf("\n");
}

/**
 * store specified bits from the specified index to
 * 	the specified address.
 *
 * @param	src
 * @param	start	- the start index.
 * @param	bits	- number of bits to store.
 * @param	dst	- data to store.
 * @param	idx	- the start index.
 */
void cel_mem_store(const void * _src, unsigned int start, unsigned int bits, void * _dst, unsigned int idx)
{
	unsigned char *__src = (unsigned char *)_src;
	unsigned char *__dst = (unsigned char *)_dst;
	register unsigned int i;

	for(i = 0; i < bits; i++)
	{
		if(CEL_BIT_FETCH(__src, start + i) != 0)
			CEL_BIT_OPEN(__dst, idx + i);
		else
			CEL_BIT_SHUT(__dst, idx + i);
	}	
}


/* get the bytes of a specified file */
long long cel_filesize(char *file)
{
	FILE * fp;
	long long length = 0;

	if((fp = fopen(file, "rb")) == NULL)
		return -1;
	else 
	{
		fseek(fp, 0L, SEEK_END);
		length = ftell(fp);
		fclose(fp);
	}

	return length;
}
